package com.bawei.day18_mediaplayer2.service;

import android.app.IntentService;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import androidx.annotation.Nullable;

public class DownloadService extends IntentService {

    public DownloadService() {
        super("DownloadService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        //下载文件
        try {
            String url1 = intent.getStringExtra("url");
            Log.d("ytx", "onHandleIntent: "+url1);
            String name = intent.getStringExtra("name");
            URL url = new URL(url1);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(6000);
            urlConnection.setConnectTimeout(6000);
            urlConnection.connect();
            InputStream inputStream = urlConnection.getInputStream();
            //获得sd卡music文件夹的路径 ===》"/sdcard/Music"
            File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
            FileOutputStream fileOutputStream = new FileOutputStream(file.getAbsolutePath()+"/"+name+".mp3");
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes))!=-1){
                fileOutputStream.write(bytes,0,len);
            }


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
